package com.cskaoyan.wx.controller;

import com.cskaoyan.bean.bo.LastIpBO;
import com.cskaoyan.bean.login_demo.BaseRespVo;
import com.cskaoyan.bean.reverseengineering.MarketUser;
import com.cskaoyan.shiro.MarketToken;
import com.cskaoyan.util.EmailUtils;
import com.cskaoyan.util.Md5Utils;
import com.cskaoyan.wx.bean.WxAdminInfoBean;
import com.cskaoyan.wx.bean.WxLoginUserData;
import com.cskaoyan.wx.service.WxAuthService;
import com.google.gson.Gson;
import org.apache.commons.mail.EmailException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @description:
 * @date: 2022/05/07 14:47
 * @author: beiji
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    @Autowired
    WxAuthService wxAuthService;

    /**
     * 用户登录功能
     *
     * @author beiji
     * @since 2022/05/07 21:39
     */
    @PostMapping("login")
    public BaseRespVo<WxLoginUserData> login(@RequestBody Map map, HttpServletRequest request) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        password = Md5Utils.getMd5(password);

        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new MarketToken(username, password, "wx"));
        } catch (AuthenticationException e) {
            return BaseRespVo.ok(null, "用户帐号或密码不正确", 700);
        }

        MarketUser user = wxAuthService.login(username);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                String newIp = request.getRemoteAddr();
                String lastLoginIp = wxAuthService.lastLoginIp(username);

                RestTemplate client = new RestTemplate();
                Gson gson = new Gson();

                ResponseEntity<String> oldEntity = client.getForEntity("https://www.douyacun.com/api/openapi/geo/location?ip=" + lastLoginIp + "&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SWQiOiIwOTVlYzVhMmMzMzcxNWVlYmFjZWFjNDk2M2Q3N2JkOCJ9.5RXMLgwQg5ZVLWWecUb5MIh7GPbHrXNlBts14bKzWKI", String.class);
                LastIpBO lastIpBO = gson.fromJson(oldEntity.getBody(), LastIpBO.class);
                String lastCity = lastIpBO.getData().getCity();

                ResponseEntity<String> newEntity = client.getForEntity("https://www.douyacun.com/api/openapi/geo/location?ip=" + newIp + "&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SWQiOiIwOTVlYzVhMmMzMzcxNWVlYmFjZWFjNDk2M2Q3N2JkOCJ9.5RXMLgwQg5ZVLWWecUb5MIh7GPbHrXNlBts14bKzWKI", String.class);
                LastIpBO newIpBO = gson.fromJson(newEntity.getBody(), LastIpBO.class);
                String newCity = newIpBO.getData().getCity();


                if (!lastCity.equals(newCity)) {
                    // 发短信吧
                    // 111.175.54.194 武汉i
                    // 0:0:0:0:0:0:0:1 会解析成上海 实际上是本地
                    // 每次登陆会把新ip写进数据库
                    try {
                        EmailUtils.send("尊敬的:" + user.getNickname() + System.lineSeparator() + "您上次登陆的地区:" + lastCity + System.lineSeparator() + "与本次登陆的地区:" + newCity + System.lineSeparator() + "不符，请注意", "1072492246@qq.com"); // 改成李鑫的邮箱
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }
                }
                wxAuthService.updateLastLogin(newIp, new Date(), username);
            }
        });

        thread.start();

        WxLoginUserData loginUserData = new WxLoginUserData();

        WxAdminInfoBean adminInfo = new WxAdminInfoBean();
        adminInfo.setAvatarUrl(user.getAvatar());
        adminInfo.setNickName(user.getNickname());

        loginUserData.setUserInfo(adminInfo);
        // loginUserData.setToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0aGlzIGlzIG1hcmtldCB0b2tlbiIsImF1ZCI6Ik1JTklBUFAiLCJpc3MiOiJNQVJLRVQiLCJleHAiOjE2NTE5MTI4ODMsInVzZXJJZCI6MSwiaWF0IjoxNjUxOTA1NjgzfQ.bUTbi90YaHg2D-9VMmhK4Aexb5OhDCAEFUcU0aWDArw");
        loginUserData.setToken((String) subject.getSession().getId());
        return BaseRespVo.ok(loginUserData, "成功", 0);
    }

    /**
     * 用户退出登录功能
     *
     * @author beiji
     * @since 2022/05/07 21:39
     */
    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok(null, "成功");
    }


}
